package com.have.blog.web.redis.impl;

import com.have.blog.base.constant.BaseRedisConstant;
import com.have.blog.config.service.RedisService;
import com.have.blog.model.models.User;
import com.have.blog.web.redis.UserRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserRedisServiceImpl implements UserRedisService {
    @Autowired
    private RedisService redisService;
    @Value("${redis.admin.database}")
    private String REDIS_KEY_DATABASE;

    @Override
    public User getUserByToken(String accessToken) {
        String key = REDIS_KEY_DATABASE + BaseRedisConstant.SEGMENTATION +
                BaseRedisConstant.USER_TOKEN + BaseRedisConstant.SEGMENTATION +
                accessToken;
        return (User) redisService.get(key);
    }

    @Override
    public void addUserByToken(String token, User user) {
        String key = REDIS_KEY_DATABASE + BaseRedisConstant.SEGMENTATION +
                BaseRedisConstant.USER_TOKEN + BaseRedisConstant.SEGMENTATION +
                token;
        redisService.set(key, user, 1, TimeUnit.HOURS);
    }

    @Override
    public void delUserByToken(String token) {
        String key = REDIS_KEY_DATABASE + BaseRedisConstant.SEGMENTATION +
                BaseRedisConstant.USER_TOKEN + BaseRedisConstant.SEGMENTATION +
                token;
        redisService.del(key);
    }
}
